package com.akuhome.resource.service.entity;

import com.akuhome.resource.DO.MyUserDetail;
import com.akuhome.resource.dao.UserDao;
import com.akuhome.resource.entity.Auth;
import com.akuhome.resource.entity.User;
import com.akuhome.resource.enums.ResultEnum;
import com.akuhome.resource.exception.ResourceException;
import com.akuhome.resource.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserService implements UserDetailsService {
    @Autowired
    UserDao userDao;
    @Autowired
    PartService partService;
    @Autowired
    PermissionService permissionService;
    @Autowired
    CharacterService characterService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User user = userDao.findUserByUsername(s);
        if(user == null){
            throw new UsernameNotFoundException("用户名不存在！");
        }
        List<Auth> auths = permissionService.findAuthByCharacterId(user.getCharacter().getId());
        MyUserDetail myUserDetail = new MyUserDetail(user.getUsername(),user.getPassword(),user.isEnable());
        List<GrantedAuthority> authorities = new ArrayList<>();
        auths.forEach(auth -> {
            authorities.add(new SimpleGrantedAuthority(auth.getRole()));
        });
        myUserDetail.setAuthorities(authorities);
        return myUserDetail;
    }

    public void register(User user){
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        Integer insertResult = userDao.insertUser(user);
        partService.addUserCount(user.getPart().getId(),1);
        characterService.addCharacterUserCount(user.getCharacter().getId(),1);
        if(insertResult != 1){
            throw new RuntimeException("注册失败");
        }
    }

    public User getCurrentUser(){
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        User user = null;
        if(principal instanceof MyUserDetail){
            user = userDao.findUserByUsername(((MyUserDetail)principal).getUsername());
        }
        return user;
    }

    public String getCurrentUsername(){
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if(principal instanceof MyUserDetail){
            return((MyUserDetail)principal).getUsername();
        }
        return null;
    }

    public Integer getCurrentUserId(){
        User user = getCurrentUser();
        return user == null? null :user.getId();
    }

    public void updateUserStatus(Integer userId,Boolean enable){
        Integer row = this.userDao.updateUserStatus(userId,enable);
        if(row != 1){
            throw new ResourceException(ResultEnum.ARG_MISMATCH_ERROR);
        }
    }

    public List<User> findAllUser(){
        return userDao.findAllUser();
    }
}
